// pagesEnterprise/pages/housingInsert/housingInsert.js
import ajax from "../../../utils/index";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    housingTypeList: ['写字楼', '商铺', '土地'],
    formData: {
      /**
       * 房产对象
       */
      housingAssess: {
        province: null, // 省 
        city: null, // 地级市 
        county: null, // 区县
        town: null, // 街道、镇
        address: null, // 详细地址 
        gardenHomeId: null, // 所属园区id 
        houseAgentId: null, // 经纪人id：可以解绑、更换或选择无经纪人；0无经纪人 
        houseArea: null, // 房屋实际面积 
        houseType: null, // 房屋类型：1园区；2写字楼；3商铺；4厂房；5仓库；6土地 
        housingMasterId: null, // 房东id 
        orientation: null, // 朝向 
        pattern: null, // 房源格局 
        provinceCityCountyId: null, // 省市区ID 
        storeyHeight: null, // 层高
        roomNumber: null, // 楼号.单元号.房号 
        buildingNo: null, // 楼号
        unitNo: null, // 单元
        roomNo: null, // 房号
        adcode: null // 区id
      },
      /**
       * 房产图片
       */
      housingAssessImage: null,
      /**
       * 房东对象
       */
      housingMaster: {
        cardId: null, // 身份证号
        cardPhotoBack: null, // 身份证照片反面 
        cardPhotoJust: null, // 身份证照片正面 
        name: null, // 房东姓名 
        phone: null, // 房东手机号 
      },
      houseRent: {
        coverLabel: null, // 封面标签 
        fitmentCase: null, // 装修情况
        highlights: null, // 房源亮点 
        housingLabel: null, // 房源标签 
        housingName: null, // 房源名称 
        leaseTerm: null, // 租期
        paymentMethod: null, // 付款方式 
        type: null, // 发布房源类型 0:房东 1经纪人 
        univalenceDay: null, // 单价/天 
        univalenceMonth: null, // 单价/月 
        utilizationRate: null, // 使用率 
        videoPath: null, // 视频路径
        workCount: null, // 工位数量
      },
      housingRentImage: []
    },
    detailId: null, // 详情Id
    step: 1, // 步骤
    gardenInfo: null, // 园区详情对象
    isSubmit: false, // 提交按钮状态
    /**
     * 经纪人列表 查询条件
     */
    queryData: {
      search: '',
      pageSize: 10,
      pageNum: 1,
      total: 0,
    },
    dataList: [], // 经纪人列表
  },
  backStepEvent() {
    this.setData({ step: 2 })
  },
  /**
   * 选择经纪人事件
   */
  radioEvent(event) {
    const item = event.currentTarget.dataset.item
    this.setData({ 'formData.housingAssess.houseAgentId': item.id })
    this.isSubmitChange()
  },
  /**
   * 选择框事件
   */
  pickerChange(event) {
    const key = event.currentTarget.dataset.key
    const startValue = event.detail.startValue
    let index = event.detail.startIndex
    if (key.indexOf('houseTypeName') != -1) this.setData({ ['formData.housingAssess.houseType']: index + 1 });
    if (key.indexOf('typeName') != -1) this.setData({ ['formData.houseRent.type']: index });
    this.setData({ ['formData.' + key]: startValue })
    this.isSubmitChange()
  },
  /**
   * 下一步 事件
   */
  nextStepEvent() {
    if (this.data.step == 3) return (this.isSubmitChange(), this.onSubmit())
    this.setData({ step: this.data.step += 1, isSubmit: false })
    wx.setNavigationBarTitle({ title: `新增房源${this.data.step}/3` })
    this.isSubmitChange()
    if (this.data.step == 3) this.getAgentList()
  },
  async onSubmit() {
    const formData = JSON.parse(JSON.stringify(this.data.formData))
    const { buildingNo, unitNo, roomNo } = formData.housingAssess
    formData.housingAssess.roomNumber = `${buildingNo},${unitNo},${roomNo}`
    formData.housingAssessImage = [{ image: formData.housingAssessImage }]
    const url = this.data.detailId ? '/my/house/assess/garden/update' : '/my/house/assess/garden/add'
    await ajax.post(url, formData)
    await ajax.showSuccess('操作成功!')
    wx.navigateBack()
  },
  /**
   * input 变化事件
   */
  formChange(event) {
    const key = event.currentTarget.dataset.key
    const value = event.detail
    this.setData({ ['formData.' + key]: value })
    this.isSubmitChange()
  },
  /**
   * 校验字段
   */
  isSubmitChange() {
    const { housingAssess, housingMaster, housingAssessImage, houseRent, housingRentImage } = this.data.formData;
    const { province, city, county, gardenHomeId, houseArea, houseType, orientation, pattern, storeyHeight, buildingNo, unitNo, roomNo, houseAgentId } = housingAssess
    const { cardPhotoBack, cardPhotoJust, name, phone, cardId } = housingMaster
    const { coverLabel, fitmentCase, highlights, housingLabel, housingName, leaseTerm, paymentMethod, univalenceDay, univalenceMonth, utilizationRate, videoPath, workCount } = houseRent
    let boo = true
    if (this.data.step == 1) boo = !(housingAssessImage && province && city && county && gardenHomeId && houseArea && houseType && orientation && pattern && storeyHeight && buildingNo && unitNo && roomNo && cardPhotoBack && cardPhotoJust && name && phone && cardId)
    if (this.data.step == 2) boo = !(housingRentImage.length && coverLabel && fitmentCase && highlights && housingLabel && housingName && leaseTerm && paymentMethod && univalenceDay && univalenceMonth && utilizationRate && videoPath && workCount)
    if (this.data.step == 3) boo = !(houseAgentId)
    this.setData({ isSubmit: !boo })
  },
  /**
   * 房产地址 事件
   */
  addressEvent() {
    const { formData, gardenInfo } = this.data
    console.log(gardenInfo)
    wx.chooseLocation({
      latitude: !gardenInfo.latitude || gardenInfo.latitude == 'null' ? null : gardenInfo.latitude,
      longitude: !gardenInfo.longitude || gardenInfo.longitude == 'null' ? null : gardenInfo.longitude,
      complete: (location) => ajax.getQQMap().reverseGeocoder({
        location: { latitude: location.latitude, longitude: location.longitude },
        success: (res) => {
          console.log("addressEvent----------", res)
          const { ad_info, address_component, address_reference } = res.result
          formData.housingAssess.adcode = ad_info.adcode
          formData.housingAssess.province = address_component.province, formData.housingAssess.city = address_component.city, formData.housingAssess.county = address_component.district, formData.housingAssess.town = address_reference.town.title, formData.housingAssess.address = address_reference.town.title + address_component.street_number + address_reference.landmark_l2.title;
          this.setData({ formData })
          this.isSubmitChange()
        }
      })
    })
  },
  /**
   * 图片列表 上传变化事件
   */
  uploadImageChange(event) {
    const { housingRentImage } = this.data.formData
    housingRentImage.push({ image: event.detail })
    this.setData({ "formData.housingRentImage": housingRentImage })
    this.isSubmitChange()
  },
  /**
   * 删除列表图片
   */
  deleteImageEvent(event) {
    const index = event.currentTarget.dataset.index
    const { housingRentImage } = this.data.formData
    housingRentImage.splice(index, 1)
    this.setData({ "formData.housingRentImage": housingRentImage })
    this.isSubmitChange()
  },
  /**
   * 获取园区详情
   */
  async getGardenInfo() {
    const res = await ajax.get(`/garden/info?id=${this.data.formData.housingAssess.gardenHomeId}`)
    this.setData({ gardenInfo: res.data })
  },
  /**
   * 搜索经纪人input事件
   */
  inputChange(event) {
    this.data.queryData.search = event.detail.value
  },
  /**
   * 搜索经纪人input事件
   */
  inputConfirm() {
    this.data.queryData.pageNum = 1;
    this.getAgentList()
  },
  /**
   * 获取经纪人列表
   */
  async getAgentList() {
    const { queryData, dataList } = this.data
    const res = await ajax.get('/my/house/agent/search/list', queryData)
    res.rows.forEach(item => item.phone = item.phone ? item.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : '');
    this.data.queryData.total = res.total
    this.setData({ dataList: queryData.pageNum == 1 ? res.rows : dataList.concat(res.rows) })
  },
  async getDetaiRequest() {
    const res = await ajax.get(`/my/house/assess/gardenHousingInfo?id=${this.data.detailId}`)
    res.data.housingAssessImage = res.data.housingAssessImage?.shift()?.image || null
    if (res.data.housingAssess.roomNumber) {
      const keyArr = ['buildingNo', 'unitNo', 'roomNo']
      const valArr = res.data.housingAssess.roomNumber.split(',')
      valArr.forEach((item, index) => res.data.housingAssess[keyArr[index]] = item)
    }
    res.data.housingAssess.houseTypeName = this.data.housingTypeList[res.data.housingAssess.houseType - 1] 
    console.log('res.data', res.data)
    this.setData({ formData: res.data })
    this.isSubmitChange()
  },
  async infoRquest() {
    if (this.data.detailId) await this.getDetaiRequest()
    if (this.data.formData.housingAssess.gardenHomeId) await this.getGardenInfo()
    await this.getAgentList()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.detailId) {
      wx.setNavigationBarTitle({ title: '房源信息 1/3' })
      this.data.detailId = options.detailId
    } else wx.setNavigationBarTitle({ title: '新增房源 1/3' })
    this.setData({ 'formData.housingAssess.gardenHomeId': options.gardenId || null })
    this.infoRquest()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    const { queryData, dataList } = this.data
    if (queryData.total == dataList.length || this.data.step != 3) return
    this.data.queryData.pageNum += 1;
    this.getRequestList()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})